/**
 * @description  组合跟踪
 * @author swl
 */
import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tabs, message, Switch } from 'antd';
import { ContentPackage, DATA_ENTRY, AdvancedSearch, PrimaryGhostC, NoQueryC } from '../../../comps';
import TargetTable from './targetTable';
import uuid from 'es6-uuid';
import styles from './index.less';
import ReactDOM from 'react-dom';
import delPng from '../../../assets/frame/clear.png';
import { isZiGuanEvir } from '../../../utils/commonFunc';

const { TabPane } = Tabs;
@Form.create()
class PortfolioTrackings extends PureComponent {
  state = {
    tabPage: [], // tab页显示
    activeKey: undefined,
    groupSource: [], // 产品组列表
    productSource: [], // 已选择产品列表
    productName: '', // 产品name
    isSimulate: '', // 模拟组合
    productId: '', // 产品code
    product: [], // 产品列表
    useKeys: [], // 树形选择框里选择的值
    selectId: [], // 产品组树形框选择后的id（包括父级）
    switchValue: true, // 定时刷新是否打开
    heightOrigin: undefined, // 当前组件top值,确定区间收益率按钮位置
    equityProductCode: undefined,
    // expanded: [],
  };

  componentDidMount() {
    const { dispatch } = this.props;
    isZiGuanEvir()
      ? ''
      : dispatch({
          type: 'portfolioTrackingsM/getProductData',
          payload: {},
          callback: (res) => {
            const groupSource = this.addId(res.dataSource);
            this.setState({
              groupSource,
            });
          },
        });
    this.windowChange();
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    // 从用户视图跳转过来 定位在对应的产品
    const data = sessionStorage.getItem('portfolioTracking');
    sessionStorage.removeItem('portfolioTracking');
    if (data) {
      const userViewProduct = JSON.parse(data);
      // 查询变量赋值 以及表单赋值
      this.product.props.form.setFieldsValue({
        product: `${userViewProduct.productCode} - ${userViewProduct.productName}`,
      });
      this.setState(
        {
          equityProductCode: userViewProduct.productCode,
          productGroup: undefined,
          productId: userViewProduct ? userViewProduct.productCode : undefined,
          productName: userViewProduct ? `${userViewProduct.productCode} - ${userViewProduct.productName}` : undefined,
          isSimulate: userViewProduct ? userViewProduct.isSimulate : undefined,
        },
        () => {
          this.getGroupList({ product: userViewProduct.productId });
        },
      ); // 这里的id 必须要有 不是code
    }
    let searchInfo = sessionStorage.getItem('searchInfo') ? JSON.parse(sessionStorage.getItem('searchInfo')) : {};
    sessionStorage.setItem('searchInfo', '');
    // 判断资管里的汇总监控跳转 开始
    const queryObj = isZiGuanEvir();
    if (queryObj && this.state.ziGuanKey != queryObj.ziGuanKey) {
      // 时间戳不相等 更新
      searchInfo = {
        productId: queryObj.productId,
        isSimulate: queryObj.isSimulate,
        title: decodeURI(queryObj.title),
      };
      this.setState({
        ziGuanKey: queryObj.ziGuanKey, // 保存url里的时间戳
      });
    }
    // 判断资管里的汇总监控跳转 结束
    if (searchInfo && searchInfo.productId) {
      this.product.props.form.setFieldsValue({
        product: `${searchInfo.productId} - ${searchInfo.title}`,
        productGroup: undefined,
      });
      this.setState(
        {
          productGroup: undefined,
          productId: searchInfo.productId,
          productName: `${searchInfo.productId} - ${searchInfo.title}`,
          isSimulate: searchInfo.isSimulate,
        },
        () => {
          this.getGroupList({ product: searchInfo.productId });
        },
      );
    }
    if (nextProps.nowKey == true && this.timer == 'clear' && this.state.switchValue) {
      if (this.state.activeKey) {
        this.timer = setInterval(() => {}, 10000);
        const key = `TargetTable${this.state.activeKey}`;
        this.state[key]?.refresh();
      }
    } else if (nextProps.nowKey == false) {
      // 离开前清除掉定时器
      this.timer && clearInterval(this.timer);
      this.timer = 'clear';
      // tab页隐藏时，取消定时刷新
      this.state.tabPage.map((item, index) => {
        const refName = `TargetTable${index + 1}`;
        this.state[refName]?.clearTime();
      });
    }
  }

  componentWillUnmount() {
    // 离开前清除掉定时器
    this.timer && clearInterval(this.timer);
    this.timer = null;
    sessionStorage.setItem('searchInfo', '');
    // tab页隐藏时，取消定时刷新
    this.state.tabPage.map((item, index) => {
      const refName = `TargetTable${index + 1}`;
      this.state[refName]?.clearTime();
    });
  }

  // 窗口大小变更触发
  windowChange = () => {
    setTimeout(() => {
      try {
        // 获取组件当前位置,确定区间收益率按钮位置
        const domTop = ReactDOM.findDOMNode(this).getBoundingClientRect();
        this.setState({
          heightOrigin: domTop.top,
        });
      } catch (err) {
        this.setState({
          heightOrigin: 50,
        });
      }
    }, 0);
  };

  // 产品组表格添加唯一标识
  addId = (datas, isproduct = false) => {
    const arr = [];
    datas.forEach((item) => {
      if (!item.children && isproduct) {
        item.children = [];
      }
      item.sortId = uuid(32); // 生成唯一的标识
      arr.push(item);
      if (item.children && item.children.length > 0) {
        this.addId(item.children, isproduct);
      }
      if (isproduct) {
        item.product = true;
        item.child = this.addId(item.children, isproduct);
      }
    });
    return arr;
  };

  // 产品组select变化
  productGroupChange = (e) => {
    // 选择产品组清空产品
    this.product.props.form.setFieldsValue({
      product: undefined,
    });
    this.setState({
      productGroup: e,
      productName: '',
      isSimulate: '',
      productId: '',
    });
  };

  // 产品select变化
  productChange = (e) => {
    if (!isZiGuanEvir()) {
      this.product.props.form.setFieldsValue({
        productGroup: undefined,
      });
      this.setState({
        productGroup: undefined,
        productId: e ? e.info.productCode : undefined,
        productName: e ? e.info.title : undefined,
        isSimulate: e ? e.info.isSimulate : undefined,
      });
    } else {
      this.setState({
        productId: e ? e.info.productCode : undefined,
        productName: e ? e.info.title : undefined,
        isSimulate: e ? e.info.isSimulate : undefined,
      });
    }
  };

  // 产品组选择值的事件
  groupSelect = (value, node, extra) => {
    const datas = [];
    datas.push(value);
    this.setState({ selectId: [...new Set(this.state.selectId.concat(datas))] });
  };

  // 产品组取消选择事件
  groupDelselect = (value, node, extra) => {
    // this.compareDatas = [];
    // let datas = [];
    this.setState({
      selectId: this.state.selectId.filter((ele) => ele !== value),
    });
  };

  // 将树形选择框数据更改为两层树形结构
  changeTree = (arr) => {
    const datas = [];
    if (arr && arr.length) {
      arr.map((item) => {
        datas.push({
          title: item.portfolioName,
          value: item.sortId,
          key: item.sortId,
          children: item.children && item.children.length ? this.changeTree2(item.children) : null,
        });
      });
    }
    return datas;
  };

  // 更改树形数据
  changeTree2 = (arr) => {
    const data = [];
    if (arr && arr.length) {
      arr.map((item) => {
        data.push({
          title: item.portfolioName,
          value: item.sortId,
          key: item.sortId,
        });
      });
    }
    return data;
  };

  // 更改资产类别
  changeAsset = (data) => {
    const arr = [];
    data.map((item) => {
      const obj = {
        value: item.code,
        title: item.value,
        children: item.children && item.children.length ? changeAsset(item.children) : null,
      };
      arr.push(obj);
    });
    return arr;
  };

  // 工具栏渲染
  renderToolbar() {
    const {
      form: { getFieldsValue, resetFields, setFieldsValue },
      loading,
      globalM: {
        dataDictionary: { PORT_MONITOR_ASSET_TYPE = [] },
      },
    } = this.props;
    const { groupSource, product } = this.state;
    const treeDatas = this.changeTree(groupSource);
    const assetTypes = this.changeAsset(PORT_MONITOR_ASSET_TYPE);

    const searchProps = {
      dataSource: isZiGuanEvir()
        ? [
            {
              dataIndex: 'product',
              title: '产品名称',
              type: DATA_ENTRY.PRODUCTLIST,
              dataType: 5,
              allowClear: true,
              onRef: (ref) => (this.product = ref),
              onChange: this.productChange,
              due: 1,
            },
            {
              dataIndex: 'assetTypes',
              title: '资产类别',
              type: DATA_ENTRY.TREESELECT,
              isMultiple: true,
              dataSource: assetTypes,
              allowClear: true,
              treeCheckable: true,
            },
            {
              dataIndex: 'industry',
              title: '所属行业',
              type: DATA_ENTRY.INDUSTRYC,
              isUnfold: false,
              multiple: true,
            },
          ]
        : [
            {
              dataIndex: 'productGroup',
              title: '产品组',
              type: DATA_ENTRY.TREESELECT,
              dataSource: treeDatas,
              isMultiple: true,
              treeCheckable: true,
              allowClear: true,
              maxTagCount: 0,
              onRef: (ref) => (this.productGroup = ref),
              onChange: this.productGroupChange,
              onSelect: (value, node, extra) => this.groupSelect(value, node, extra), // 选中值后将父级id及本身id放入state管理
              onDeselect: (value, node, extra) => this.groupDelselect(value, node, extra), // 取消选中后将父级id及本身id放入state管理
            },
            {
              dataIndex: 'product',
              title: '产品名称',
              type: DATA_ENTRY.PRODUCTLIST,
              dataType: 5,
              allowClear: true,
              onRef: (ref) => (this.product = ref),
              onChange: this.productChange,
              due: 1,
            },
            {
              dataIndex: 'assetTypes',
              title: '资产类别',
              type: DATA_ENTRY.TREESELECT,
              isMultiple: true,
              dataSource: assetTypes,
              allowClear: true,
              treeCheckable: true,
            },
            {
              dataIndex: 'industry',
              title: '所属行业',
              type: DATA_ENTRY.INDUSTRYC,
              multiple: true,
              isUnfold: false,
            },
          ],
      selfButt: (
        <PrimaryGhostC
          title='刷新'
          onClick={() => {
            const values = this.product.props.form.getFieldsValue();
            if (values.product || values.productGroup) {
              if (this.state.activeKey) {
                const key = `TargetTable${this.state.activeKey}`;
                this.state[key]?.refresh();
              }
            } else {
              message.info('未匹配，请输入查询条件。');
            }
          }}
          style={{ marginLeft: '16px' }}
        />
      ),
      onQuery: (e) => {
        // tab页隐藏时，取消定时刷新
        this.state.tabPage.map((item, index) => {
          const refName = `TargetTable${index + 1}`;
          this.state[refName]?.clearTime();
        });
        if (e.product) {
          this.getGroupList(e);
        } else {
          this.changeTabs(e);
        }
      },
      onClear: () => {
        resetFields();
      },
    };

    return <AdvancedSearch {...searchProps} />;
  }

  // tab切换时调用
  handleChangeTab = (value) => {
    if (value == 'deleteAll') {
      const index = parseInt(this.state.activeKey);
      const arr = this.state.tabPage.slice(index - 1, index);
      this.setState(
        {
          tabPage: arr,
          activeKey: '1',
          productName: '',
          isSimulate: '',
          productId: '',
        },
        () => {
          this.setSearch(1);
        },
      );
    } else {
      this.setSearch(value);
      this.state[`TargetTable${value}`].setState({ expandRow: [] });
      this.setState({
        activeKey: value,
      });
    }
  };

  // 获取产品下组合维度
  getGroupList = (e) => {
    const { productId } = this.state;
    this.props.dispatch({
      type: 'portfolioTrackingsM/getGroupList',
      payload: {
        productCode: productId,
      },
      callback: (res) => {
        const that = this;
        const productSource = [];
        if (res && res.length) {
          const treeDatas = this.addId(res, true);
          productSource.push(...treeDatas);
          this.setState(
            {
              productSource,
            },
            () => {
              that.changeTabs(e);
            },
          );
        }
      },
    });
  };

  // 查询时tab修改
  changeTabs = (e) => {
    const { selectId, groupSource, tabPage, productId, isSimulate, activeKey, productName, productSource, productGroup } = this.state;
    const arr = [...tabPage];
    const obj = {
      assetTypes: e.assetTypes,
      industry: e.industry,
    };
    let pageCurrent;
    // 判断tab页是否已经存在产品/产品组，若存在值修改tab页e
    let hasTab = false;
    // 当前tab页已经存在产品/产品组，查询条件是否变化
    let haschange = false;
    if (e.productGroup) {
      obj.selectId = selectId;
      obj.useDataSource = groupSource;
      obj.name = '产品组';
      obj.isgroup = true;
      obj.productGroup = productGroup;
      arr.map((item, index) => {
        if (item.isgroup) {
          haschange = item.industry != e.industry || item.assetTypes != e.assetTypes;
          item.selectId = obj.selectId;
          item.assetTypes = obj.assetTypes;
          item.industry = obj.industry;
          item.useDataSource = obj.useDataSource;
          item.productGroup = productGroup;
          item.name = obj.name;
          hasTab = true;
          pageCurrent = index + 1;
        }
      });
      if (!hasTab) arr.push(obj);
    } else if (e.product) {
      obj.useDataSource = [...productSource];
      obj.name = productName;
      obj.isSimulate = isSimulate;
      arr.map((item, index) => {
        if (item.useDataSource[0].portfolioCode == productId) {
          haschange = item.industry != e.industry || item.assetTypes != e.assetTypes;
          item.assetTypes = e.assetTypes;
          item.industry = e.industry;
          item.useDataSource = [...productSource];
          hasTab = true;
          pageCurrent = index + 1;
        }
      });
      if (!hasTab) arr.push(obj);
    } else {
      message.warning(`请选择${!isZiGuanEvir() ? '产品组或' : ''}产品`);
    }
    this.setState(
      {
        tabPage: arr,
        activeKey: pageCurrent ? pageCurrent.toString() : arr.length.toString(),
      },
      () => {
        // 点击查询时，判断是否要刷新（tab页已存在并且查询条件未改变时调用，查询条件改变时组件内会刷新）
        if (activeKey && hasTab && !haschange) {
          const key = `TargetTable${activeKey}`;
          this.state[key]?.refresh();
        }
      },
    );
  };

  // tab切换时，修改顶部搜索内容
  setSearch = (key) => {
    if (this.state.tabPage.length > 0) {
      const obj = this.state.tabPage[key - 1];
      if (!obj.isgroup) {
        this.product.props.form.setFieldsValue({
          product: `${obj.useDataSource[0].portfolioCode} - ${obj.useDataSource[0].portfolioName}`,
          productGroup: undefined,
        });
        this.setState({
          productName: obj.useDataSource[0].portfolioName,
          isSimulate: obj.isSimulate,
          productId: obj.useDataSource[0].portfolioCode,
        });
      } else if (obj.productGroup) {
        this.product.props.form.setFieldsValue({
          productGroup: obj.productGroup,
          product: undefined,
        });
      }
      this.product.props.form.setFieldsValue({
        assetTypes: obj.assetTypes,
        industry: obj.industry,
      });
      // tab页隐藏时，取消定时刷新
      this.state.tabPage.map((item, index) => {
        const refName = `TargetTable${index + 1}`;
        if (key != index + 1) {
          this.state[refName]?.clearTime();
        } else {
          this.state[refName]?.refresh();
        }
      });
    } else {
      this.product.props.form.setFieldsValue({
        product: undefined,
        assetTypes: undefined,
        industry: undefined,
        productGroup: undefined,
      });
    }
  };

  // tabs关闭事件
  onEdit = (targetKey, action) => {
    this[action](targetKey);
  };

  remove = (targetKey) => {
    const arr = [...this.state.tabPage];
    arr.splice(targetKey - 1, 1);
    this.setState(
      {
        tabPage: arr,
        activeKey: '1',
      },
      () => {
        this.setSearch(1);
      },
    );
  };

  // 定时刷新按钮
  switchChange = (e) => {
    const key = `TargetTable${this.state.activeKey}`;
    this.state[key]?.changeFixed('click');
    if (e) {
      this.setState({
        switchValue: true,
      });
      if (this.state.activeKey) {
        this.state[key]?.refresh();
      }
    } else {
      this.setState({
        switchValue: false,
      });
      this.state.tabPage.map((item, index) => {
        const refName = `TargetTable${index + 1}`;
        this.state[refName]?.clearTime();
      });
    }
  };

  render() {
    const { activeKey, tabPage, switchValue, heightOrigin } = this.state;
    return (
      <ContentPackage
        title={isZiGuanEvir() ? '组合监控' : '组合跟踪'}
        contentHtml={
          <div className={styles.portfolioTracking}>
            {this.renderToolbar()}
            <div style={{ position: 'relative' }}>
              {tabPage && tabPage.length ? (
                <>
                  <div style={{ position: 'absolute', top: '30px', right: '0px', zIndex: '2' }}>
                    <Switch defaultChecked={true} checked={switchValue} onChange={this.switchChange} style={{ marginRight: '10px' }} />
                    定时刷新
                  </div>
                  <Tabs hideAdd={true} activeKey={activeKey} onChange={this.handleChangeTab} onEdit={this.onEdit} type='editable-card' style={{ paddingTop: '20px' }}>
                    {tabPage.map((item, index) => {
                      const refName = `TargetTable${index + 1}`;
                      return (
                        <TabPane closable={true} tab={item.name} key={index + 1}>
                          <TargetTable
                            switchValue={switchValue}
                            heightOrigin={heightOrigin}
                            key={item.name}
                            onRef={(ref) => this.setState({ [refName]: ref })}
                            useDataSource={item.useDataSource}
                            selectId={item.selectId}
                            isgroup={item.isgroup}
                            activeKey={activeKey}
                            indexKey={index + 1}
                            assetTypes={item.assetTypes}
                            industry={item.industry}
                            isSimulate={item.isSimulate}
                          />
                        </TabPane>
                      );
                    })}
                    <TabPane closable={false} tab={<img src={delPng} />} key={'deleteAll'} />
                  </Tabs>
                </>
              ) : (
                <div style={{ marginTop: '10px' }}>
                  <NoQueryC />
                </div>
              )}
            </div>
          </div>
        }
      />
    );
  }
}
export default connect(({ portfolioTrackingM, CollectingMonitoringM, loading, globalM, keyFiguresM }) => ({
  portfolioTrackingM,
  CollectingMonitoringM,
  loading,
  globalM,
  keyFiguresM,
}))(PortfolioTrackings);
